package service;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import properties.MyAppConstantes;

import android.os.AsyncTask;
import beans.User;
import controller.MainActivity;

/**
 * @author ALENGUYE
 *
 */
public class SearchUsersAsyncTask extends AsyncTask<Object, Void, List<User>> {
	private MainActivity Context = null;
	private String result;
	private String hash;
	private String timestamp;
	List<User> listUsers = new ArrayList<User>();

	public SearchUsersAsyncTask(MainActivity context) {
		Context = context;
	}

	@Override
	protected void onPreExecute() {
	}

	@Override
	protected List<User> doInBackground(Object... params) {

		HttpClient client = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost("http://" + MyAppConstantes.WsIpServer
				+ ":8080/ab_service_mgr/api/mobile/search");

		ResponseHandler<String> responseHandler = new BasicResponseHandler();

		httpPost.setHeader("content-type", "application/json");

		try {
			timestamp = System.currentTimeMillis() + "";
			hash = Sha1Utils.sha(MyAppConstantes.wsSecret + timestamp);

			JSONObject json = new JSONObject();
			json.put("timestamp", timestamp);
			json.put("hash", hash);
			json.put("wsCallerId", MyAppConstantes.wsCallerId);

			StringEntity entity = new StringEntity(json.toString());
//			entity.setChunked(false);

			httpPost.setEntity(entity);
			httpPost.setHeader("Content-Type", "application/json");
			// entity.setContentEncoding("application/json");

			result = client.execute(httpPost, responseHandler);
			JSONObject jsonResp = new JSONObject(result);
			JSONArray arrayUsers = jsonResp.getJSONArray("userDto");

			int nbUsers = arrayUsers.length();
			for (int j = 1; j <= nbUsers; j++) {
				User user = new User(arrayUsers.getJSONObject(j - 1).getString(
						"identifiant"), arrayUsers.getJSONObject(j - 1)
						.getString("nom"), arrayUsers.getJSONObject(j - 1)
						.getString("prenom"), arrayUsers.getJSONObject(j - 1)
						.getString("photoURL"), arrayUsers.getJSONObject(j - 1)
						.getString("status"));

				listUsers.add(user);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return listUsers;
	}

	protected void onPostExecute(List<User> listUsers) {
		Context.setListUsers(listUsers);
		Context.searchUserForm(listUsers);
	}
}
